import { createLogger } from 'redux-logger';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage/session';
import autoMergeLevel1 from 'redux-persist/lib/stateReconciler/autoMergeLevel1';

import { modalError } from 'utils/feedbacks';

/**
 * redux-persist配置
 */
const reduxPersistConfig = {
  key: 'root',
  storage,
  stateReconciler: autoMergeLevel1,
  whitelist: ['ucenter'],
};

/**
 * dva配置
 */
export const dva = {
  config: {
    onAction: createLogger(),

    async onError(error) {
      error.preventDefault();
      console.log('全局异常：');
      console.log(error);

      const { code, msg, callback } = error;
      await modalError(msg);

      // 对于特殊的code，进行特殊的处理
      switch(code) {
        // 登录失败
        case 40001: 
          // 全局获取dispatch
          const { dispatch } = window.g_app._store;
          // 清空ucenter缓冲，重新登录
          dispatch({ type: 'ucenter/userLogout' });
          return;
        default:
          break;
      }

      !!callback && callback();
    },
    
    onReducer(reducer) {
      return persistReducer(reduxPersistConfig, reducer);
    },
  },
};